package com.oildatacollection.util;

import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class YamlLoader {
    private final String filePath;
    private Map<String, Object> ymlObj;

    public YamlLoader(String path) {
        this.filePath = Objects.requireNonNull(this.getClass().
                getClassLoader().getResource(path)).getPath();
        InputStream input = null;
        ymlObj = null;
        try {
            input = new FileInputStream(filePath);
            Yaml yaml = new Yaml();
            ymlObj = (Map<String, Object>) yaml.load(input);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("未找到文件", e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    log.error("文件流关闭失败", e);
                }
            }
        }
    }

    public Object get(String key) {
        if (ymlObj == null) {
            return null;
        }
        return ymlObj.get(key);
    }


}
